# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, request, jsonify, current_app, redirect, url_for, g
from web.models.user import User
from common.libs.UserService import UserService
from application import db

route_user = Blueprint('user_page', __name__)


@route_user.route("/login", methods=["GET", "POST"])
def login():
    if request.method == 'GET':
        return render_template("user/login.html")
    # 以下是post请求执行的代码
    # 1.接受客户端提交过来的用户登录数据
    resp = {
        "code": 200,
        "msg": "登录成功",
        "data": {}
    }
    req = request.values
    login_name = req["login_name"] if "login_name" in req else ""
    login_pwd = req["login_pwd"] if "login_pwd" in req else ""
    if (not login_name) or len(login_name) < 1:  # 当账号为空或者账号长度小于1的时候，修改对应的状态码，以及相应的提示提示，
        resp["code"] = -1
        resp["msg"] = "请输入正确的登录用户名"
        return jsonify(resp)
    if (not login_pwd) or len(login_pwd) < 1:  # 当密码为空或者密码长度小于1的时候，修改对应的状态码，以及相应的提示
        resp["code"] = -1
        resp["msg"] = "请输入正确的密码"
        return jsonify(resp)
    # 验证
    # 使用模型验证用户名和密码
    user_info = User.query.filter_by(login_name=login_name).first()
    if not user_info:  # 数据库查不到，该账号未注册
        resp["code"] = -1
        resp["msg"] = "请输入正确的用户名或密码"
        return jsonify(resp)
    salt = user_info.login_salt  # 拿到数据表中加盐字符串
    gen_pwd = UserService.genPwd(login_pwd, salt)  # 跟注册时相同的加密机制
    if user_info.login_pwd != gen_pwd:
        resp["code"] = -1
        resp["msg"] = "请输入正确的用户名或密码"
        return jsonify(resp)
    # 登录成功
    resp['data']['username'] = login_name
    resp['data']['password'] = login_pwd
    # 上面验证都通过如下：
    # 1.输入账号、密码的输入格式进行验证
    # 2.账号、密码和数据表数据进行验证
    # 接下来就需要进行，设置cookie来保持会话，如果我们已经登录过，下次再来进行访问的时候，可以直接跳转到详情页，否则跳转到登录界面
    response = jsonify(resp)
    cookie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
    response.set_cookie(current_app.config.get('AUTH_COOKIE_NAME'), cookie_str)
    return response


@route_user.route("/logout")
def logout():
    response = redirect(url_for('user_page.login'))
    response.delete_cookie(current_app.config['AUTH_COOKIE_NAME'])
    return response


@route_user.route("/edit", methods=["GET", "POST"])
def edit():
    '''编辑个人信息'''
    if request.method == "GET":
        return render_template("user/edit.html")
    # 以下是post请求情况
    resp = {
        "code": 200,
        "msg": "操作成功",
        "data": {}
    }
    req = request.values
    nickname = req["nickname"] if "nickname" in req else ""
    email = req["email"] if "email" in req else ""

    if (not nickname) or len(nickname) < 1:
        resp["code"] = -1
        resp["msg"] = "请输入符合规范的姓名"

        return jsonify(resp)
    if (not email) or len(email) < 1:
        resp["code"] = - 1
        resp["msg"] = "请输入符合规范的邮箱"

        return jsonify(resp)
    # 修改当前登录人姓名和邮箱
    user_info = g.current_user
    user_info.nickname = nickname
    user_info.email = email

    # 提交数据库
    db.session.add(user_info)
    db.session.commit()

    return jsonify(resp)


@route_user.route("/reset-pwd", methods=["GET", "POST"])
def resetPwd():
    '''修改用户密码'''
    if request.method == "GET":
        '''判断进入的跳转到的页面到底是账号编辑页面，还是添加账号页面'''
        context = {}
        req = request.args
        id = int(req.get("id", 0))
        reback_url = url_for('member_page.index')
        if id < 1:
            return redirect(reback_url)
        info = None
        if id:
            info = User.query.filter_by(id=id).first()
        context["info"] = info
        return render_template("member/set.html", **context)
    # 下面是post请求的实现
    resp = {
        "code": 200,
        "msg": "修改密码成功",
        "data": {}
    }
    req = request.values
    old_password = req["old_password"] if "old_password" in req else ""
    new_password = req["new_password"] if "new_password" in req else ""

    if (not old_password) or len(old_password) < 1:
        resp["code"] = -1
        resp["msg"] = "请输入正月的原密码"
        return jsonify(resp)
    if (not new_password) or len(new_password) < 1:
        resp["code"] = -1
        resp["msg"] = "请输入不少于6位的新密码"
        return jsonify(resp)

    if old_password == new_password:
        resp["code"] = -1
        resp["msg"] = "新旧密码一致"
        return jsonify(resp)
    # 校验旧密码
    user_info = g.current_user
    salt = user_info.login_salt
    gen_pwd = UserService.genPwd(old_password, salt)  # 跟注册时相同的加密机制
    if user_info.login_pwd != gen_pwd:
        resp["code"] = -1
        resp["msg"] = "原密码不对~"
        return resp
    # 更新密码到数据库
    user_info.login_pwd = UserService.genPwd(new_password, salt)
    # 提交数据库
    db.session.add(user_info)
    db.session.commit()
    # 更新cookie
    # 生成新的cookie
    response = jsonify(resp)
    # 携带cookie
    cookie_str = UserService.genAuthCode(user_info)
    response.set_cookie(current_app.config.get("AUTH_COOKIE_NAME"), cookie_str)
    return jsonify(resp)


